package com.d3works.apps.supplychain.db.repo;

import com.d3works.apps.account.db.Invoice;
import com.d3works.apps.account.db.InvoiceLine;
import com.d3works.apps.account.db.repo.InvoiceManagementRepository;
import com.d3works.apps.sale.service.app.AppSaleService;
import com.d3works.apps.supplychain.service.invoice.InvoiceServiceSupplychain;
import com.d3works.exception.service.TraceBackService;
import com.d3works.inject.Beans;
import javax.persistence.PersistenceException;

public class InvoiceSupplychainRepository extends InvoiceManagementRepository {

  @Override
  public Invoice copy(Invoice entity, boolean deep) {
    Invoice copy = super.copy(entity, deep);

    copy.setSaleOrder(null);
    copy.setPurchaseOrder(null);
    copy.setStockMoveSet(null);

    if (copy.getInvoiceLineList() != null && !copy.getInvoiceLineList().isEmpty()) {
      for (InvoiceLine line : copy.getInvoiceLineList()) {
        line.setSaleOrderLine(null);
        line.setPurchaseOrderLine(null);
        line.setStockMoveLine(null);
        line.setOutgoingStockMove(null);
        line.setIncomingStockMove(null);
      }
    }
    return copy;
  }

  @Override
  public Invoice save(Invoice invoice) {
    try {
      InvoiceServiceSupplychain invoiceServiceSupplychain =
          Beans.get(InvoiceServiceSupplychain.class);

      if (Boolean.TRUE.equals(
          Beans.get(AppSaleService.class).getAppSale().getEnablePackManagement())) {
        invoiceServiceSupplychain.computePackTotal(invoice);
      } else {
        invoiceServiceSupplychain.resetPackTotal(invoice);
      }

      return super.save(invoice);
    } catch (Exception e) {
      TraceBackService.traceExceptionFromSaveMethod(e);
      throw new PersistenceException(e.getMessage(), e);
    }
  }
}
